<template>
  <view class="webview-container">
    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="back-icon" @click="goBack">
        <image src="/static/arrow-left.png" mode="aspectFit"></image>
      </view>
      <view class="title">{{ title }}</view>
      <view class="close-icon" @click="close">
        <text>×</text>
      </view>
    </view>
    
    <!-- 网页内容 -->
    <web-view :src="url" @message="handleMessage" @error="handleError"></web-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      url: '',
      title: '网页浏览'
    }
  },
  onLoad(options) {
    if (options.url) {
      this.url = decodeURIComponent(options.url);
      
      // 尝试从URL中提取标题
      try {
        const urlObj = new URL(this.url);
        this.title = urlObj.hostname;
      } catch (e) {
        console.error('解析URL出错:', e);
      }
    }
  },
  methods: {
    goBack() {
      // 网页后退
      const webview = this.$mp.page.$getAppWebview().children()[0];
      if (webview.canGoBack()) {
        webview.goBack();
      } else {
        uni.navigateBack();
      }
    },
    close() {
      // 关闭整个页面
      uni.navigateBack();
    },
    handleMessage(e) {
      console.log('接收到网页消息:', e.detail);
    },
    handleError(e) {
      console.error('网页加载错误:', e);
      uni.showToast({
        title: '网页加载失败',
        icon: 'none'
      });
    }
  }
}
</script>

<style lang="scss">
.webview-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.nav-bar {
  margin-top: 60rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  padding: 0 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  
  .back-icon {
    font-size: 40rpx;
    color: #333;
    padding: 10rpx;
    
    image {
      width: 32rpx;
      height: 32rpx;
      display: block;
    }
  }
  
  .title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
    max-width: 60%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .close-icon {
    font-size: 48rpx;
    color: #333;
    padding: 10rpx;
    line-height: 1;
  }
}

web-view {
  flex: 1;
}
</style>
